package edison.utils;

import org.apache.commons.lang.StringUtils;

public abstract class Path {

	private static String format(String path) {
		if (!path.equals("/") && path.endsWith("/"))
			return StringUtils.removeEnd(path, "/");

		return path;

	}

	public static String combine(String... paths) {
		StringBuilder pathBuilder = new StringBuilder(paths.length * 8);
		for (String path : paths) {
			pathBuilder.append(path);
		}

		return pathBuilder.toString().replaceAll("//", "/");
	}

	public static String relPath(String absPath, String relPath) {
		return null;
	}

	public static String getName(String path) {
		if (path.equals("/"))
			return "/";
		String[] parts = path.split("/");
		return parts[parts.length-1];
	}

	/**
	 * 获取当前路径的父路径
	 * 
	 * @param path
	 *            当前路径
	 * @return 返回父路径，如果当前路径已经是根路径，则返回null
	 */
	public static String getParent(String path) {
		if (path.equals("/"))
			return null;

		path = format(path);
		int index = path.lastIndexOf("/");
		return path.substring(0, index);
	}

	public static String getAncestor(String path, int depth) {
		String[] parts = path.split("/");
		if (depth > parts.length)
			return null;

		StringBuilder pathBuilder = new StringBuilder();
		for (int i = 0; i < depth; i++) {
			pathBuilder.append("/").append(parts[i]);
		}

		return pathBuilder.toString();
	}
}
